package com.zyht.bank.manage.controller;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.wx.entity.SysWebArticle;
import com.wx.model.BussinessException;
import com.wx.model.article.SiteModel;
import com.wx.service.ArticlemsgService;
import com.wx.service.SaveArticleParameter;
import com.zyht.common.AbsBaseController;
import com.zyht.common.util.Page;

/**
 * 问答管理
 * 
 * @author qjl
 * @data 2017年6月29日
 */

@Controller
@RequestMapping("admin/ques")
public class AdminQuestionController extends AbsBaseController {

	@Resource
	private ArticlemsgService articleService;

	@RequestMapping("index")
	public String index(Integer currentPage, Long siteid, String search, Model model) {
		if (currentPage == null) {
			currentPage = 1;
		}

		Page<SysWebArticle> page = articleService.getListByPage(currentPage, siteid);
		List<SiteModel> siteAll = articleService.getSite();
		model.addAttribute("siteAll", siteAll);
		model.addAttribute("siteid", siteid);
		model.addAttribute("page", page);
		model.addAttribute("search", search);

		return "banks/manage/quest/detail/quesindex";
	}

	@RequestMapping("saveview")
	public String saveview(Model model, Long article_id) {

		if (article_id == null) {
			model.addAttribute("article", new SysWebArticle());
		} else {
			SysWebArticle article = articleService.getArticle(article_id);
			if (article == null) {
				return message("未知文章", "admin/ques/index", model);
			}
			model.addAttribute("article", article);
		}
		return "banks/manage/quest/detail/saveview";
	}

	@RequestMapping("save")
	public String save(@RequestParam(value = "id", required = false) Long id,
			@RequestParam(value = "name", required = false) String name,
			@RequestParam(value = "publish", required = false) String publish,
			@RequestParam(value = "content", required = false) String content, Model model) {

		SaveArticleParameter bean = new SaveArticleParameter();

		if (name == null) {
			throw new BussinessException("文章标题不正确");
		}

		if (publish == null) {
			throw new BussinessException("发布时间不正确");
		}

		if (content == null) {
			throw new BussinessException("正文不正确");
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date parse = null;
		try {
			parse = sdf.parse(publish);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		bean.setName(name);
		bean.setContent(content);
		bean.setPublish(parse);

		Long article_id = id;
		if (article_id == null) {
		} else {
			SysWebArticle al = articleService.getArticle(article_id);
			if (al == null) {
				throw new BussinessException("文章编号不正确");
			}
		}
		articleService.doSaveArticle(bean, article_id);
		model.addAttribute("msg", "保存成功！");
		model.addAttribute("redirect", "admin/ques/index");
		return "message";
	}

	@RequestMapping("del/{id}/{currentPage}")
	public String removeArtilcleById(@PathVariable("id") Integer id, @PathVariable("currentPage") Integer currentPage,
			HttpSession session) {
		if (null != id) {
			try {
				String rootPath = session.getServletContext().getRealPath("");
				SysWebArticle article = articleService.getArticle(Long.valueOf(id));
				String content = article.getContent();
				List<String> imgStr = getImgStr(content);
				for (String img : imgStr) {
					String[] split = img.split("upload");
					String realPath = rootPath.concat("/upload").concat(split[1]);
					File file = new File(realPath);
					if (file.exists()) {
						file.delete();
					}
				}
			} catch (Exception e) {
				logger.error("删除文章图片：" + e.getMessage());
			}
			this.articleService.deleteArticleById(Long.valueOf(id));
		}
		return "redirect:/admin/articlemsg/index?currentPage=" + currentPage.intValue();
	}

	private List<String> getImgStr(String htmlStr) {
		String img = "";
		Pattern p_image;
		Matcher m_image;
		List<String> pics = new ArrayList<String>();
		String regEx_img = "<img.*src=(.*?)[^>]*?>"; // 图片链接地址
		p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
		m_image = p_image.matcher(htmlStr);
		while (m_image.find()) {
			img = img + "," + m_image.group();
			Matcher m = Pattern.compile("src=\"?(.*?)(\"|>|\\s+)").matcher(img);// 匹配src
			while (m.find()) {
				pics.add(m.group(1));
			}
		}
		return pics;
	}

	private String message(String msg, String redirect, Model model) {
		model.addAttribute("msg", msg);
		model.addAttribute("redirect", redirect);
		return "message";
	}
}
